(function (w,undefined) {
    let game;
    function Game(map) {
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        game = this;
    }

    Game.prototype.start = function () {
        this.food.render(this.map);
        this.snake.render(this.map);
        runSnake();
        bindKey();
    };

    function bindKey() {
        document.addEventListener('keydown',function (e) {
            switch(e.code) {
                case 'KeyW':
                    this.snake.direction = 'top';
                    break;
                case 'KeyS':
                    this.snake.direction = 'bottom';
                    break;
                case 'KeyA':
                    this.snake.direction = 'left';
                    break;
                case 'KeyD':
                    this.snake.direction = 'right';
                    break;
            }
        }.bind(game),false)

    }
    function runSnake() {
        let timerId = setInterval(function () {
            this.snake.move(this.food,this.map);
            this.snake.render(this.map);
            let maxX = this.map.offsetWidth/this.snake.width;
            let maxY = this.map.offsetHeight/this.snake.height;
            let headX= this.snake.body[this.snake.body.length-1].x;
            let headY= this.snake.body[this.snake.body.length-1].y;
            if (headX <0 || headY >=maxY || headX > maxX) {
                alert('游戏结束');
                clearInterval(timerId)
            }
        }.bind(game), 100)
    }

    w.Game = Game;
})(window,undefined);
